// Conversion.cs
// 
// All the autors on autors.txt
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using Gtk;

namespace Zencoder
{
	public delegate void StartConversionEventHandler(object sender, EventArgs e);
	
	public delegate void StopConversionEventHandler(object sender, EventArgs e);
	
	public class Conversion : System.Diagnostics.Process
	{
		public event StartConversionEventHandler StartConversionEvent;
		public event StopConversionEventHandler StopConversionEvent;
		
		private int videoBitrate, audioBitrate;
		private string filename, outputfilename, outputpath;
		
		private static object lockI = new System.Object();
		
		public string Filename{get{return this.filename;}}
		public string Outputfilename{get{return this.outputfilename;}}
		public string Outputpath{get{return this.outputpath;}}	

		
		public Conversion(string filename, int videoBitrate)
		{
			this.filename = filename;
			this.videoBitrate = videoBitrate;
			this.audioBitrate = 0;
			this.StartInfo.FileName = "mencoder";
			this.EnableRaisingEvents = false;
			this.outputfilename = this.filename.Substring(filename.LastIndexOf("/")+1);
			this.outputpath = this.filename.Substring(0,filename.LastIndexOf("/"));
		}

		public Conversion(string filename, int videoBitrate, int audioBitrate) : this(filename, videoBitrate)
		{
			this.audioBitrate = audioBitrate;
		}
		
		public void DoConversion()
		{
			lock(Conversion.lockI)
			{
				if (this.audioBitrate != 0)
					this.StartInfo.Arguments = " -vf scale=320:-10,expand=320:240 -oac mp3lame -lameopts abr:br="
						+ audioBitrate + " -ovc xvid -xvidencopts bitrate=" + videoBitrate + " '" + filename
						+ "' -o '" + outputpath + "/" + outputfilename.Substring(0,outputfilename.LastIndexOf("."))
						+ " [Zen].avi'";
				else
					this.StartInfo.Arguments = " -vf scale=320:-10,expand=320:240 -oac mp3lame -ovc xvid -xvidencopts bitrate="
						+ videoBitrate + " '" + filename + "' -o '" + outputpath + "/"
						+ outputfilename.Substring(0,outputfilename.LastIndexOf(".")) + " [Zen].avi'";
				
				System.Console.WriteLine(this.StartInfo.Arguments);
				
				this.Start();
				this.WaitForExit();

				//listStore.GetIterFirst (out iter);
				//listStore.Remove(ref iter);
				// this will wait for the pulsing to finish
				System.Threading.Thread.Sleep (100);
				Console.WriteLine("finito doconversion");
			}
		}/**/
	}
}